﻿//用div布局表格
/*
.td不要设置margin、padding。通过.td中的span来设置.
*/
$c.fn.table = function (config) {
    //var g = {}; //global,全局
    var obj = function (selector, config) {
        this.selector = selector;
        this.config = $.extendEx({}, this.defConfig, config);
        $(this.selector).addClass('kui-table');
    }
    obj.prototype.defConfig = {
    };
    obj.prototype.getTrHeight = function (tr) {
        var _this = this;
        var tdList = $('>.kui-td', tr);
        var maxHeight = 0;
        $.each(tdList, function (i, td) {
            var tdHeight = 0;
            //var trList = $($('.tr'), td);//不对
            var trList = $(td).find('>.kui-tr');
            var table = $(td).find('>.kui-table');
            if (table.length == 1) {
                tdHeight = _this.correctTrHeight($(table));
            }
            else if (trList.length > 0) {
                $.each(trList, function (_i, _tr) {
                    tdHeight += _this.getTrHeight(_tr);
                });
            }
            else {
                tdHeight = $(td).height();
                var _span = $(td).children('span');
                if (_span.length != 1) {
                    alert('td中有且仅有一个span');

                }
                var _spanHeight=_span.outerHeight(true);
                if (_spanHeight > tdHeight) {
                    tdHeight = _spanHeight;
                }
            }
            if (tdHeight > maxHeight) {
                maxHeight = tdHeight;
            }
        });
        tdList.height(maxHeight);
        //tdList.css('line-height', maxHeight);
        return maxHeight;
    }
    obj.prototype.correctTrHeight = function (table) {
        var _this = this;

        var tdList = $(table).find('.kui-td');
        $.each(tdList, function (i, td) {
            var _initHeight = $(td).attr('_initHeight');
            if (!_initHeight) {
                var tdHeight = Math.round(parseFloat($(td).css('height').split('px')[0]));
                $(td).attr('_initHeight', tdHeight);//列调窄时内容把表撑高,列调宽时表格高度要再降低回到初始高度.
            }
            else {
                $(td).css('height', parseInt(_initHeight, 10));
                //$(td).css('line-height', parseInt(_initHeight, 10));
            }
        });


        //var trList = $('.table>.tr');
        var trList = $(table).find(">.kui-tr");
        $.each(trList, function (i, tr) {
            var trHeight = _this.getTrHeight(tr);
            $('>.kui-td', tr).height(trHeight);
            //$('>.kui-td', tr).css('line-height',trHeight);
        });
        return $(table).outerHeight(true);
    }
    obj.prototype.correctTdWidth = function (table) {
        //因为表中可以嵌套表，所以不能直接这样:$(table).find('.td');
        var _this = this;

        var tableWidth = Math.round($(table).width());
        var parent = $(table).parent();
        if (parent.hasClass('kui-td')) {
            tableWidth = Math.round(parent.width());
        }
        var firstTrTdList = $(table).find('>.kui-tr:eq(0)>.kui-td');
        var assignableWidthTotal = tableWidth;//可分配宽度.
        var tdWidthTotal = 0;
        var borderWidthTotal = 0;
        var fixColIndexList = [];
        var notFixColIndexList = [];
        //fixColWidth只在初始化的时候用,即使为1仍可拖动调整宽度.
        $.each(firstTrTdList, function (i, headTd) {
            var _w = Math.round(parseFloat($(headTd).css('width').split('px')[0]));
            if ($(headTd).attr('fixColWidth') != '1') {
                tdWidthTotal += _w;
                notFixColIndexList.push(i);
            }
            else {
                assignableWidthTotal -= _w;
                fixColIndexList.push(i);
            }
            if (i > 0) {
                borderWidthTotal += Math.round(parseFloat($(headTd).css('border-left-width').split('px')[0]));
            }
        });
        assignableWidthTotal -= borderWidthTotal;
        var assignedWidth = 0;//已分配宽度
        $.each(firstTrTdList, function (i, headTd) {
            var tdWidth = 0;
            var cssWidth = Math.round(parseFloat($(headTd).css('width').split('px')[0]));
            if (fixColIndexList.indexOf(i) != -1) {//固定
                tdWidth = cssWidth;
            }
            //else if (i == firstTrTdList.length - 1) {
            else if(notFixColIndexList[notFixColIndexList.length-1]==i){//最后一个不固定列.
                tdWidth = assignableWidthTotal - assignedWidth;
            }
            else {
                tdWidth = cssWidth * assignableWidthTotal / tdWidthTotal;
                tdWidth = Math.round(tdWidth);
                assignedWidth += tdWidth;
            }
            var _tdList = $(table).find('>.kui-tr>.kui-td.kui-td-' + (i + 1) + ',>.kui-tr>.kui-td>.kui-tr>.kui-td.kui-td-' + (i + 1) + ',>.kui-tr>.kui-td>.kui-tr>.kui-td>.kui-tr>.kui-td.kui-td-' + (i + 1) + '');
            _tdList.css('width', tdWidth);
        });

        var tdList = $(table).find('>.kui-tr>.kui-td,>.kui-tr>.kui-td>.kui-tr>.kui-td,>.kui-tr>.kui-td>.kui-tr>.kui-td>.kui-tr>.kui-td');
        $.each(tdList, function (i, td) {
            var childTable = $(td).find('>.kui-table');
            if (childTable.length > 0) {
                _this.correctTdWidth(childTable);
            }
        });
    }
    
    obj.prototype.table = function (table) {
        if (!table) {
            table = this.selector;
        }
        //先执行correctTdWidth再执行correctTrHeight.因为宽度改变后内容会导致高度改变.
        this.correctTdWidth(table);
        this.correctTrHeight(table);
        var sepContainer = table.sepContainer;
        
        if (!sepContainer) {
            sepContainer = $('<div style="position:fixed;left:0;top:0;margin:0;width:0;z-index:' + ($g.zIndex++) + '"></div>');//width:0:这样不会遮住内容.kwindow的z-index应设为比这个大.
            $("body").prepend(sepContainer);//要插到最前面,如果放在最后面,会遮住前面的内容,导致内容只能看见不能操作.
            table.sepContainer = sepContainer;
            sepContainer.sepList = [];
            $.each(table.find('>.kui-tr:eq(0)>.kui-td'), function (i, td) {
                if (i == 0) {
                    return;
                }
                var sep = $('<div class="kui-sep-resize" style="position: absolute;cursor: ew-resize;width:2px;border-width:0;"></div>').appendTo(sepContainer);//width:2px比较好,容易点中,如果设置为0则点不中也看不到。
                sepContainer.sepList.push(sep);

                var border_left_width = parseFloat($(td).css('border-left-width').split('px')[0]);
                sep.css('border-left-width', border_left_width);
                sep.css('border-left-style', $(td).css('border-left-style'));
                sep.css('border-left-color', $(td).css('border-left-color'));
                
                //注间：表中可嵌套表，leftCol、rightCol不能包含嵌套表中的列
                sep.leftCol = table.find('>.kui-tr>.kui-td.kui-td-' + i + ',>.kui-tr>.kui-td>.kui-tr>.kui-td.kui-td-' + i + ',>.kui-tr>.kui-td>.kui-tr>.kui-td>.kui-tr>.kui-td.kui-td-' + i + '');
                sep.rightCol = table.find('>.kui-tr>.kui-td.kui-td-' + (i + 1) + ',>.kui-tr>.kui-td>.kui-tr>.kui-td.kui-td-' + (i + 1) + ',>.kui-tr>.kui-td>.kui-tr>.kui-td>.kui-tr>.kui-td.kui-td-' + (i + 1) + '');

                sep.updateCol = function (offset) {

                    //分页的时候,表html格是重新生成的,所以要重新设置sep.leftCol,sep.rightCol.
                    sep.leftCol = table.find('>.kui-tr>.kui-td.kui-td-' + i + ',>.kui-tr>.kui-td>.kui-tr>.kui-td.kui-td-' + i + ',>.kui-tr>.kui-td>.kui-tr>.kui-td>.kui-tr>.kui-td.kui-td-' + i + '');
                    sep.rightCol = table.find('>.kui-tr>.kui-td.kui-td-' + (i + 1) + ',>.kui-tr>.kui-td>.kui-tr>.kui-td.kui-td-' + (i + 1) + ',>.kui-tr>.kui-td>.kui-tr>.kui-td>.kui-tr>.kui-td.kui-td-' + (i + 1) + '');
                    
                    sep.leftCol.width(sep.leftCol.width() + offset);
                    sep.rightCol.width(sep.rightCol.width() - offset);

                    _obj.table(table);
                };

                sep.mousedown(function (e) {
                    _obj.dragSeparate = sep;
                    sep.startX = e.pageX;
                    sep.preX = e.pageX;

                    return false;//返回false阻止事件冒泡,否则移动过程中会复制文本
                });
            });
        }

        $.each(table.find('>.kui-tr:eq(0)>.kui-td'), function (i, td) {
            if (i == 0) {
                return;
            }
            var sep = table.sepContainer.sepList[i - 1];
            $(sep).css('top', $(td).offset().top - $(document).scrollTop());
            //alert(table.height());
            $(sep).css('height', table.height());
            $(sep).css('left', $(td).offset().left);
            //alert($(td).offset().left);
            sep.rightCol.css('border-left-color', table.css('background-color'));//对于边框为点线的情况,由于sep与td左边框上下不能完全重合,导致部分看起来像实线.
        });

        if (config&&config.onResize) {
            config.onResize();
        }
    }

    var selector=this.jo;
    var _obj = new obj(selector, config || {});
    _obj.table();

    $(window).resize(function () {
        _obj.table();
    });

    $(window).scroll(function () {
        _obj.table();
    });

    $(document).mousemove(function (e) {
        if (!_obj.dragSeparate) {
            return;
        }
        if (!_obj.dragSeparate.startMove) {
            _obj.dragSeparate.startMove = true;
            _obj.dragSeparate.rightCol.css('border-left-color', _obj.dragSeparate.css('border-left-color'));
        }

        var cssLeft = $(_obj.dragSeparate).css('left');
        var left = cssLeft.substr(0, cssLeft.length - 2);
        left = parseFloat(left);
        $(_obj.dragSeparate).css('left', left + (e.pageX - _obj.dragSeparate.preX));
        _obj.dragSeparate.preX = e.pageX;

        return false;//返回false阻止事件冒泡,否则移动过程中会复制文本

    });

    $(document).mouseup(function (e) {
        if (!_obj.dragSeparate) {
            return;
        }
        _obj.dragSeparate.startMove = false;
        var subtractValue = e.pageX - _obj.dragSeparate.startX;
        

        _obj.dragSeparate.updateCol(subtractValue);//如果把resizeSeparate一直拖动到表格外部,通过update()自动调整回来.

        _obj.dragSeparate = null;
        return false;//返回false阻止事件冒泡
    });

    return _obj;
};